<?php
/**
 * Created by PhpStorm.
 * User: x  新版pcAPI
 * Date: 2018/11/28
 * Time: 10:32
 */

namespace app\newapi\controller;
use think\Controller;
use think\Db;
use app\common\model\WxUser as WxUserModel;
use app\common\model\Users as UsersModel;
use app\common\model\Csuser as CsuserModel;
use app\common\util\WechatThirdUtil;
use think\Request;
// 新增后台试用账号
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use think\Session;

class User extends Controller
{
    protected $config;
    protected $wx_user;
    protected $users_model;
    protected $csuser_model;
    private $request_uri;
    private $request_uri3;
    protected $admin_user_model;
    protected $auth_group_access_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user = new WxUserModel();
        $this->csuser_model = new CsuserModel();
        $this->users_model = new UsersModel();
        $this->config = $this->wx_user->find();
        $this->request_uri = NODE_URL.'/receiveMsg';
        $this->request_uri3 = NEW_NODE_URL.'/receiveMsg';
        $this->admin_user_model   = new AdminUserModel();
        $this->auth_group_access_model = new AuthGroupAccessModel();
    }

    /*
     * 20190213
     * 发送消息返回存储id
     * */
    public function sengMsgForUser(){
        // 發送消息給用戶
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];
            $customerService = isset($data['customerService']) ? $data['customerService'] : '';
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            if (!empty($customerService)) {
                $result = $wechatObj->appointSendMsgToOne($openid, $content, $customerService);
            } else {
                $result = $wechatObj->sendMsgToOne($openid, $content);
            }
            if ($result) {
                $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
                $post_arr = [
                    'type' => $data['type'],
                    'content' => $content, //消息文本
                    'openid' => $openid, //用户openid
                    'appid' => $appid, //对应公众号appid
                    'cs_id' => $data['cs_id'], //客服id
                    'send_time' => $data['send_time'], //发送时间
                    'send_type' => '1002',
                    'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                    'fromname' => $pid == 0 ? $pid : $data['cs_id'] ,  // 消息来自于组长
                ];
                // 判断消息的发送人  组长还是组员
                //测试储存链接的外部数据库
                //获取储存对应数据库名  ,'is_talk' => 1
                $sqlname = 'chatlog' . $data['cs_id'] % 10;
                $this->users_model->where(['butt_id'=>$post_arr['cs_id'],'openid'=>$openid])->update(['last_butt_time'=>time(),'groupid' => 1]);
//                $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                $ret = Db::connect('db_config_chatlog')->name($sqlname)->insertGetId($post_arr);
                $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                if ($ret) {
                    return json_encode([
                        'status' => 1,
                        'msg' => '发送成功',
                        'id' => $ret ,
                        'send_time' => time()], JSON_UNESCAPED_UNICODE);
                }
            }else{
                return json_encode(['status' => -1, 'error' => '发送失败'], JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['status' => -1, 'error' => '非法請求'], JSON_UNESCAPED_UNICODE);
        }
    }
    /*
     * 普通向用户发送图片消息
     * 加上可以群发图片消息 V 1.0
     * */
    public function sengImgForUser()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 判断media_id 是否为空,如果不存在就上传图片,存在就直接发送
            if(empty($data['media_id'])){
                $file = $this->request->file('image');
                $result = $this->resource($data, $file, 'image');
                if ($result) {
                    return $result;
                } else {
                    return json_encode(['status' => -1, 'error' => 'resource upload error'], JSON_UNESCAPED_UNICODE);
                }
            }else{
                $result = null;
                $appid = $data['appid'];
                $openid = $data['openid'];
                $customerService = isset($data['customerService']) ? $data['customerService'] : '';
                $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
                $wechatObj = new WechatThirdUtil($this->config, $author_wx);
                if (!empty($customerService)) {
                    $result = $wechatObj->appointSendMediaToOne($data['openid'], $data['media_id'], 'image', $customerService);
                }else{
                    $result = $wechatObj->sendMediaToOne($data['openid'], $data['media_id'], 'image');
                }

                if ($result) {
                    $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
                    $post_arr = [
                        'type' => $data['type'],
                        'content' =>$data['content'], //图片路径
                        'openid' => $data['openid'], //用户openid
                        'appid' => $data['appid'], //对应公众号appid
                        'cs_id' => $data['cs_id'], //客服id
                        'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                        'send_type' => '1002',
                        'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                    ];
                    //获取储存对应数据库名  ,'is_talk' => 1
                    $this->users_model->where(['butt_id'=>$post_arr['cs_id'],'openid'=>$openid])->update(['last_butt_time'=>time(),'groupid' => 1]);
                    $sqlname = 'chatlog'.$data['cs_id'] % 10;
//                    $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                    $ret = Db::connect('db_config_chatlog')->name($sqlname)->insertGetId($post_arr);
                    $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                    // $ret = Db::name('chatlog')->insert($post_arr);
                    if ($ret) {
                        return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $data['content'], 'send_time' => time(),'id'=>$ret], JSON_UNESCAPED_UNICODE);
                    }else{
                        return json_encode(['status' => 303, 'error' => '写入数据库失败'], JSON_UNESCAPED_UNICODE);
                    }
                } else {
                    return json_encode(['status' => 301, 'error' => '发送图片失败'], JSON_UNESCAPED_UNICODE);
                }
            }
        } else {
            return json_encode(['status' => 404, 'error' => '非法请求'], JSON_UNESCAPED_UNICODE);
        }
    }
    
    // 直接通过链接获取media_id
    public function img_oss_mediaid(){
        $appid = 'wxdce09ad7ceab8ae8';
        // 
        $img_path_url = 'https://node6.shangning.site/getOssFile?objname=uploads/20181108/146cc1ad52c6a199ba576d6e67b1e93d.jpg';
        $img_path_url = 'http://hcfasion.oss-cn-hangzhou.aliyuncs.com/uploads/20181108/146cc1ad52c6a199ba576d6e67b1e93d.jpg?OSSAccessKeyId=LTAIKqa4XUOwajiT&Expires=1544329509&Signature=l3YtXVlEe8RKlLRmM9SpB9llFPs%3D';
        $author_wx = M('author_wx_user')->where('appid', $appid)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $chat_resource = $wechatObj->uploadTempMaterial($img_path_url);
        return  json([
            'status' => 200,
            'data' => $chat_resource
        ]);
    }

    /**
     * 向用户发送语音信息.
     */
    public function sendVoiceForUser()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $file = $this->request->file('voice');
            // dump($file);exit();
            $result = $this->resource($data, $file, 'voice');
            if ($result) {
                return $result;
            } else {
                return json_encode(['status' => -1, 'error' => 'resource upload error'], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => '煞笔，哈哈'], JSON_UNESCAPED_UNICODE);
        }
    }

    // 发送文本 图片 音频 视频消息后 存储消息到数据库 更新 think_users 里面的 last_butt_time  groupid
    private function msgUpdateTime($post_arr,$author_wx){
        $sqlname = 'chatlog' . $post_arr['cs_id'] % 10;
        $map = ['butt_id'=>$post_arr['cs_id'],'openid'=>$post_arr['openid']];
        $this->users_model->where($map)->update(['last_butt_time'=>time(),'groupid' => 1]);
        $ret = Db::connect('db_config_chatlog')->name($sqlname)->insertGetId($post_arr);
        $this->mo_send_type($author_wx['id'], $author_wx['uid']);
        if ($ret) {
            return json_encode([
                'status' => 1,
                'msg' => '发送成功',
                'id' => $ret ,
                'send_time' => time()], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 从微信api获取用户信息.
     * @param appid 公众号appid
     * @param openid 用户openid
     */
    public function getUserInfo($appid, $openid)
    {
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $result = $wechatObj->getFanInfo($openid);
        if ($result) {
            //更新用户信息
            $update_data = [
                'nickname' => $result['nickname'],
                'sex' => $result['sex'],
                'city' => $result['city'],
                'province' => $result['province'],
                'country' => $result['country'],
                'headimgurl' => $result['headimgurl'],
                'subscribe_scene' => $result['subscribe_scene'],
            ];
            $update_user = $this->users_model->where('openid',$openid)->update($update_data);
            if(! $update_user){
                Db::name('logs')->insert(['openid'=>$openid,'content'=>'从微信服务器获取用户信息到user表失败','create_time'=>time()] );
            }
            return json_encode(['status' => 1, 'result' => $result], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }
    
    // 从微信服务器获取用户信息,不更新到用户数据库
    public function getUserInfo_bk($appid, $openid)
    {
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $result = $wechatObj->getFanInfo($openid);
        if ($result) {
            return json_encode(['status' => 1, 'result' => $result], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /**
     * 从数据库获取用户信息.
     *
     * @param openid 用户id
     */
    public function getSqlUserInfo_bk($openid)
    {
        $result = $this->users_model->alias('u')->where('openid', $openid)->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')->find();
        if ($result) {
            return json_encode(['status' => 1, 'result' => $result], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /*
     * 从数据库获取用户信息.
     * 附带最后一条聊天记录
     * */
    public function getSqlUserInfo($openid)
    {
        // 返回用户信息的同时返回备注信息 users_added
        $result = $this->users_model->alias('u')->where('openid', $openid)->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')->find();
        $last_msg = Db::connect('db_config_chatlog')->name('chatlog')->where('openid', $openid)->order('id desc')->limit(1)->select();
        if ($result) {
            return json_encode(['status' => 1, 'result' => $result , 'last_msg' => $last_msg], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /**
     * 获取聊天记录，包括需要推送的消息.
     *
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function getChatLogAll()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (M('csuser')->where('id', $data['cs_id'])->value('pid') == 0) {
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where('pid', $data['cs_id'])->where('openid', $data['openid'])->order('id desc')->select();
            } else {
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where('cs_id', $data['cs_id'])->where('openid', $data['openid'])->order('id desc')->select();
            }
            if ($result) {
                return json_encode(['status' => 1, 'chatlog' => $result]);
            } else {
                return json_encode(['status' => -1, 'error' => 'error']);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /**
     * 获取聊天记录，包括需要推送的消息.
     * ==> 临时改成获取全部聊天记录  旧版本获取了组员的聊天记录
     * @param openid 用户openid
     * @param cs_id 客服id
     * @param offset 偏移量
     * @param log_id 聊天记录id
     * @param count 数量
     */
    public function getChatLog_old()
{
    if ($this->request->isPost()) {
        $data = $this->request->post();
        $cs_id = $data['cs_id'];
        $openid = $data['openid'];
        $last_time = isset($data['last_time']) ? $data['last_time'] : '';
        $offset = isset($data['offset']) ? ($data['offset'] < 10 ? $data['offset'] : 10) : 0;
        $count = isset($data['count']) ? ($data['count'] < 10 ? $data['count'] : 10) : 10;
        if (M('csuser')->where('id', $data['cs_id'])->value('pid') == 0) {
            $where = [
                'pid' => ['eq', $cs_id],
                'openid' => ['eq', $openid],
            ];
        } else {
            $where = [
                'cs_id' => ['eq', $cs_id],
                'openid' => ['eq', $openid],
            ];
        }

        if ($offset != 0) {
            $count = $offset - $count;
        }
        if(empty($last_time)){
            $result = Db::connect('db_config_chatlog')->name('chatlog')
                ->where($where)->limit($offset, $count)
                ->order('id desc')->select();
        }else{
            $where['send_time'] = ['lt', $last_time];
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset, $count)->order('id desc')->select();
        }

        if ($result) {
            return json_encode(['status' => 1, 'chatlog' => $result]);
        } else {
            return json_encode(['status' => -1, 'error' => 'error', 'chatlog' => '']);
        }
    } else {
        return json_encode(['status' => -1, 'error' => 'error']);
    }
}

    // 新版获取聊天记录
    public function getChatLog()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $cs_id = $data['cs_id'];
            $openid = $data['openid'];
            $last_time = isset($data['last_time']) ? $data['last_time'] : '';
            $offset = isset($data['offset']) ? ($data['offset'] < 10 ? $data['offset'] : 10) : 0;
            $count = isset($data['count']) ? ($data['count'] < 10 ? $data['count'] : 10) : 10;
            // 根据csid获取组长组员信息
            $csids = $this->getIds($cs_id);
            $where = [
                'cs_id' => ['in', $csids],
                'openid' => ['eq', $openid],
            ];
            if ($offset != 0) {
                $count = $offset - $count;
            }
            if(empty($last_time)){
                $result = Db::connect('db_config_chatlog')->name('chatlog')
                    ->where($where)->limit($offset, $count)
                    ->order('id desc')->select();
            }else{
                $where['send_time'] = ['lt', $last_time];
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset, $count)->order('id desc')->select();
            }
            if ($result) {
                return json_encode(['status' => 1, 'chatlog' => $result]);
            } else {
                return json_encode(['status' => -1, 'error' => 'error', 'chatlog' => '']);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    public function getChatLog_t($openid,$csid){
        $last_time = '';
        $offset =  0;
        $count =  10;
        // 根据csid获取组长组员信息
        $csids = $this->getIds($csid);
        $where = [
            'cs_id' => ['in', $csids],
            'openid' => ['eq', $openid],
        ];
        
        if ($offset != 0) {
            $count = $offset - $count;
        }
        if(empty($last_time)){
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset, $count)->order('id desc')->select();
        }else{
            $where['send_time'] = ['lt', $last_time];
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset, $count)->order('id desc')->select();
        }
        
        if ($result) {
            return json_encode(['status' => 1, 'chatlog' => $result]);
        } else {
            return json_encode(['status' => -1, 'error' => 'error', 'chatlog' => '']);
        }
    }


    /**
     * 获取需要推送的聊天消息.
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function getPushMsg()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq', $data['cs_id']],
                'needsend' => ['eq', 1],
            ];
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->order('id desc')->select();
            //获取完聊天记录后把状态改回0
            if ($result) {
                Db::connect('db_config_chatlog')->name('chatlog')->where($where)->update(['needsend' => 0]);

                return json_encode(['status' => 1, 'pushmsg' => $result]);
            } else {
                return json_encode(['status' => -1, 'error' => 'error']);
            }
        }
    }

    /**
     * 已读推送消息，取消推送状态提醒.
     *
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function clearPushMsg()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq', $data['cs_id']],
                'openid' => ['eq', $data['openid']],
                'needsend' => ['eq', 1],
            ];

            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->update(['needsend' => 0]);
            if ($result) {
                return json_encode(['status' => 1, 'msg' => '状态已清除']);
            } else {
                return json_encode(['status' => -1, 'error' => '状态清除失败']);
            }
        }
    }

    /**
     * 给用户打标签.
     *
     * @param type appid
     * @param type tagid
     * @param type openid
     */
    public function setUserTags()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $appid = $data['appid'];
            // $openid_list[] = $data['openid'];
            $openid = $data['openid'];
            $tagid = $data['tagid'];
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            $result = $wechatObj->batchUsersTag([$openid], $tagid);
            if ($result) {
                $tagid_list = $this->users_model->where('openid', $openid)->value('tagid_list');
                $tagid_list_arr = unserialize($tagid_list);
                $tagid_list_arr[] = $tagid;
                $tagid_list_arr = array_unique($tagid_list_arr);
                // $res = M('users')->where('openid','IN',implode(',',$openid_list))->update(['tagid_list'=>serialize($tagid_list_arr)]);
                $res = M('users')->where('openid', $openid)->update(['tagid_list' => serialize($tagid_list_arr)]);
                if (!$res) {
                    return json(['status' => -1, 'error' => 'Update user taglist error']);
                } else {
                    return json(['status' => 1, 'msg' => 'ok', 'tagid_list' => $tagid_list_arr]);
                }
            } else {
                return json(['status' => -1, 'msg' => 'Save tag to WeChat failure']);
            }
        } else {
            return json(['status' => -1, 'error' => 'method error']);
        }
    }

    /**
     * 给用户删除标签.
     *
     * @param type appid
     * @param type tagid
     * @param type openid
     */
    public function delUserTags()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $tagid = $data['tagid'];
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            $result = $wechatObj->batchCancelUsersTag([$openid], $tagid);
            if ($result) {
                $tagid_list = $this->users_model->where('openid', $openid)->value('tagid_list');
                $tagid_list_arr = unserialize($tagid_list);
                $filp_tagid_list_arr = array_flip($tagid_list_arr); //调换键值
                if (array_key_exists($tagid, $filp_tagid_list_arr)) {
                    unset($filp_tagid_list_arr[$tagid]);
                    $tagid_list_arr = array_flip($filp_tagid_list_arr);
                    $res = M('users')->where('openid', $openid)->update(['tagid_list' => serialize($tagid_list_arr)]);
                    // $res = M('users')->where('openid','IN',implode(',',$openid_list))->update(['tagid_list'=>serialize($tagid_list_arr)]);
                    if ($res) {
                        return json(['status' => 1, 'msg' => 'ok', 'tagid_list' => $tagid_list_arr]);
                    } else {
                        echo M('users')->getLastSql();
                        return json(['status' => -1, 'error' => 'Update user taglist error']);
                    }
                }
            } else {
                return json(['status' => -1, 'msg' => 'Save tag to WeChat failure']);
            }
        } else {
            return json(['status' => -1, 'error' => 'method error']);
        }
    }

    /*
     * 自动推送前15个用户信息.
     * 合并处理csid的方法
     * */
    public function autoPushMsg($cs_id){
        $map = [];
        $csid_list = $this->getIds($cs_id);
        $map['cs_id'] =  array('in',$csid_list);
        $openids = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->order('send_time desc')->limit(50)->column('openid');
        if ($openids != true) {
            return json(['status' => -1, 'error' => 'openids is empty']);
        }
        $result = $this->users_model->field('user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age,subscribe_time,butt_id')
            ->alias('u')->whereIn('openid', $openids)->where('subscribe', 1)
            ->union("SELECT user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age,subscribe_time,butt_id FROM think_users as s LEFT JOIN think_users_added as d ON s.user_id = d.uid WHERE butt_id = {$cs_id} AND subscribe = 1 LIMIT 50")
            ->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')
            ->select();
        if ($result) {
            foreach ($result as $v) {
                $chatlog = Db::connect('db_config_chatlog')->name('chatlog')->where('openid', $v['openid'])->order('send_time DESC')->limit(10)->select();
                $v['chatlog'] = array_reverse($chatlog);
            }
            return json(['status' => 1, 'msg' => 'ok', 'result' => $result]);
        } else {
            return json(['status' => -1, 'error' => 'maybe query error,please check']);
        }
    }

    // 临时测试, 获取聊天信息


    /*
     * 自动推送前15个用户信息.
     * 新版本可以查看到组长和组员发送的消息
     * */
    public function autoPushMsg_new($cs_id){
        $map = [];
        // 判断获取聊天记录的是组长还是组员
        $pid = M('csuser')->where('id', $cs_id)->value('pid');
        $csid_list = array();
        if ($pid == 0) {
            // 是组长账号
            $csids = M('csuser')->where('pid', $cs_id)->column('id');
            array_push($csids,(int)$cs_id);
            $csid_list = $csids;
        } else {
            // 如果是组员, 就获取组员自己和组长的聊天记录
            $csids = array((int)$cs_id,$pid);
            $csid_list = $csids;
        }
        // 根据返回的id获取对应的客户信息
        $map['cs_id'] =  array('in',$csid_list);
        $openids = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->order('send_time desc')->limit(50)->column('openid');
        if ($openids != true) {
            return json(['status' => -1, 'error' => 'openids is empty']);
        }
        $result = $this->users_model->field('user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age,subscribe_time,butt_id')
            ->alias('u')->whereIn('openid', $openids)->where('subscribe', 1)
            ->union("SELECT user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age,subscribe_time,butt_id FROM think_users as s LEFT JOIN think_users_added as d ON s.user_id = d.uid WHERE butt_id = {$cs_id} AND subscribe = 1 LIMIT 50")
            ->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')
            ->select();
        if ($result) {
            foreach ($result as $v) {
                $chatlog = Db::connect('db_config_chatlog')->name('chatlog')->where('openid', $v['openid'])->order('send_time DESC')->limit(10)->select();
                $v['chatlog'] = array_reverse($chatlog);
            }
            return json(['status' => 1, 'msg' => 'ok', 'result' => $result]);
        } else {
            return json(['status' => -1, 'error' => 'maybe query error,please check']);
        }
    }

    /**
     * 自动推送前15个用户信息.
     * 旧版本的只有组员的消息,没有组长的消息
     * @param type cs_id
     */
    public function autoPushMsg_old($cs_id)
    {
        if (M('csuser')->where('id', $cs_id)->value('pid') == 0) {
            $map = [    'pid' => ['eq', $cs_id],   ];
        } else {
            $map = [   'cs_id' => ['eq', $cs_id], ];
        }
        $where = [   'butt_id' => ['eq', $cs_id], 'subscribe' => ['eq', 1],  ];

        //获取聊天时间最晚的 ->group('openid')
        $openids = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->order('send_time desc')->limit(50)->column('openid');
        if ($openids != true) {
            return json(['status' => -1, 'error' => 'openids is empty']);
        }
        $result = $this->users_model->field('user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age,subscribe_time,butt_id')
            ->alias('u')->whereIn('openid', $openids)->where('subscribe', 1)
            ->union("SELECT user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age,subscribe_time,butt_id FROM think_users as s LEFT JOIN think_users_added as d ON s.user_id = d.uid WHERE butt_id = {$cs_id} AND subscribe = 1 LIMIT 50")
            ->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')
            ->select();

        //获取最晚关注的
        // $result = $this->users_model->alias('u')->where($where)
        //             ->join('think_users_added a','u.user_id = a.uid','LEFT')
        //             ->order('subscribe_time desc')->limit(15)->select();
        if ($result) {
            foreach ($result as $v) {
                $chatlog = Db::connect('db_config_chatlog')->name('chatlog')->where('openid', $v['openid'])->order('send_time DESC')->limit(10)->select();
                $v['chatlog'] = array_reverse($chatlog);
            }
            return json(['status' => 1, 'msg' => 'ok', 'result' => $result]);
        } else {
            return json(['status' => -1, 'error' => 'maybe query error,please check']);
        }
    }

    /**
     * 上传素材资源，返回资源本地路径.
     *
     * @param type image[图片] audio[音频]
     */
    protected function  resource($data, $file, $type)
    {
        $appid = $data['appid'];
        $openid = $data['openid'];
        $chat_upload = new Chatupload();
        if ($type == 'image') {
            $keyword_arr = $chat_upload->upload($file);
            // $keyword_arr = $file;
        } elseif ($type == 'voice') {
            $keyword_arr = $chat_upload->voiceUpload($file);
        }
        if ($keyword_arr['error'] == 0) {
            $keyword = $keyword_arr['url'];
        } else {
            return false;
        }
        $customerService = isset($data['customerService']) ? $data['customerService'] : '';
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $chat_resource = null;
        // 判断是否是客户端
        if (!empty($customerService)) {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->appointSendMediaToOne($openid, $chat_resource['media_id'], $type, $customerService);
        } else {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->sendMediaToOne($openid, $chat_resource['media_id'], $type);
        }

        if ($result) {
            $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
            $post_arr = [
                'type' => $data['type'],
                'content' => $keyword, //图片路径
                'openid' => $data['openid'], //用户openid
                'appid' => $data['appid'], //对应公众号appid
                'cs_id' => $data['cs_id'], //客服id
                'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                'send_type' => '1002',
                'pid' => $pid == 0 ? $data['cs_id'] : $pid,
            ];

            //获取储存对应数据库名
            //$this->users_model->where('openid', $openid)->update(['groupid' => 1]);
            $this->users_model->where(['butt_id'=>$post_arr['cs_id'],'openid'=>$openid])->update(['last_butt_time'=>time(),'groupid' => 1]);
            $sqlname = 'chatlog'.$data['cs_id'] % 10;
//            $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
            $ret = Db::connect('db_config_chatlog')->name($sqlname)->insertGetId($post_arr);
            $this->mo_send_type($author_wx['id'], $author_wx['uid']);
            // $ret = Db::name('chatlog')->insert($post_arr);
            if ($ret) {
                return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $keyword,
                    'send_time' => time(),'media_id'=>$chat_resource['media_id']
                    , 'id' => $ret], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'send error'], JSON_UNESCAPED_UNICODE);
        }
    }

    protected function resource_bk($data, $file, $type)
    {
        $appid = $data['appid'];
        $openid = $data['openid'];
        $chat_upload = new Chatupload();
        if ($type == 'image') {
            $keyword_arr = $chat_upload->upload($file);
            // $keyword_arr = $file;
        } elseif ($type == 'voice') {
            $keyword_arr = $chat_upload->voiceUpload($file);
        }
        if ($keyword_arr['error'] == 0) {
            $keyword = $keyword_arr['url'];
        } else {
            return false;
        }
        $customerService = isset($data['customerService']) ? $data['customerService'] : '';
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $chat_resource = null;
        // 判断是否是客户端
        if (!empty($customerService)) {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->appointSendMediaToOne($openid, $chat_resource['media_id'], $type, $customerService);
        } else {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->sendMediaToOne($openid, $chat_resource['media_id'], $type);
        }

        if ($result) {
            $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
            $post_arr = [
                'type' => $data['type'],
                'content' => $keyword, //图片路径
                'openid' => $data['openid'], //用户openid
                'appid' => $data['appid'], //对应公众号appid
                'cs_id' => $data['cs_id'], //客服id
                'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                'send_type' => '1002',
                'pid' => $pid == 0 ? $data['cs_id'] : $pid,
            ];

            //获取储存对应数据库名
            $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
            $sqlname = 'chatlog'.$data['cs_id'] % 10;
            $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
            $this->mo_send_type($author_wx['id'], $author_wx['uid']);
            // $ret = Db::name('chatlog')->insert($post_arr);
            if ($ret) {
                return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $keyword, 'send_time' => time(),'media_id'=>$chat_resource['media_id']], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'send error'], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 获取公众号openid.
     */
    public function getOpenidAll()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $where = [
                'subscribe' => ['eq', 1],
                'auid' => ['eq', $id],
            ];
            $openid = $this->users_model->where('auid', $id)->column('openid');
            if ($openid) {
                return json(['status' => 1, 'msg' => 'ok', 'result' => $openid]);
            }

            return json(['status' => -1, 'error' => 'not find openid']);
        }
    }

    /**
     * 实时监控发送消息.
     */
    private function mo_send_type($author_id, $uid)
    {
        $arr_data = [
            'type' => 'current_msg_count',
            'data' => [
                'id' => $author_id,
                'uid' => $uid,
            ],
        ];
        sendWebSocket($arr_data);
    }

    /*
     * 根据组长id查询对应的组员id数组
     * */
    public function leaders($cs_id){
        $pid = M('csuser')->where('id', $cs_id)->value('pid');
        if ($pid == 0) {
            // 是组长账号
            $csids = M('csuser')->where('pid', $cs_id)->column('id');
            array_push($csids,(int)$cs_id);
            return json(['code'=>1,'msg'=>'是组长账号,返回自己和所有组员id','data'=>$csids]);
        } else {
            // 如果是组员, 就获取组员自己和组长的聊天记录
            $csids = array((int)$cs_id,$pid);
            return json(['code'=>2,'msg'=>'是组员账号,返回自己和组长id','data'=>$csids]);
        }
    }

    /*
     * 根据组员id或者组长id,组长id获取所有组员id
     * */
    private function getIds($cs_id){
        $pid = M('csuser')->where('id', $cs_id)->value('pid');
        if ($pid == 0) {
            // 是组长账号
            $csids = M('csuser')->where('pid', $cs_id)->column('id');
            array_push($csids,(int)$cs_id);
            return $csids;
        } else {
            // 如果是组员, 就获取组员自己和组长的聊天记录
            $csids = array((int)$cs_id,$pid);
            return $csids;
        }
    }

    // ---------------------------------------- copy 從 wechatThirdLogic 的發送消息的方法 start ----------------------- //
    /**
     * 发送消息.
     */
    private function send($url, $post_arr)
    {
        $result = httpRequest($url, 'POST', $post_arr);
        if (!$result) {
            return false;
        }

        return $result;
    }
// ---------------------------------------- copy 從 wechatThirdLogic 的發送消息的方法 end ----------------------- //

    public function try_user(){
        if($this->request->isPost()){
            $data = $this->request->param();
            $where['password'] = md5($data['password'] . Config::get('salt'));
            $where['create_time'] = date('Y-m-d H:i:s');
            $where['username'] = $data['username'];
            $admin_add = $this->admin_user_model->allowField(true)->save($where);
            if ($admin_add) {
                $auth_group_access['uid']      = $this->admin_user_model->id;
                $auth_group_access['group_id'] = 3;
                $this->auth_group_access_model->save($auth_group_access);
                return json_encode(['status' => 1, 'msg' => '注册成功', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
            }else{
//                $this->error('注册失败');
                return json_encode(['status' => 404, 'msg' => '注册失败', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['status' => 301, 'msg' => '非法请求', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
        }
    }

}
